package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import cn.com.elite.Util;
import java.net.URLEncoder;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import java.net.URLDecoder;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @Title: BP_YG_apiUnderdelivery
 * @Description:深圳宝安排水系统-运营管理 工单数据接口--内部
 * @author: chieh*
 * @date 2020-09-07 下午17:00:00
 *
 */

public class BP_YG_apiUnderdelivery implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(BP_YG_apiUnderdelivery.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = list.get(0).get("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());

			String sys_source = GetJV(inObject, "sys_source");
			String sys_flag = GetJV(inObject, "sys_flag");//1下送  2重新派遣 3回访回退  4延期审核回复
			String workorderid = GetJV(inObject, "workorderid");
			String approvalDays = GetJV(inObject, "approvalDays");//审批天数
			String business_source = GetJV(inObject, "business_source");//业务来源
			
			log.debug("解析信息- sys_source：" + sys_source + 'sys_flag：' + sys_flag + 'workorderid：' + workorderid+ 'approvalDays：' + approvalDays+ 'business_source：' + business_source);

			def getSelectSQL = eliteBean.chaxun_sql("select o.curstep_id_map as curstep_id_map from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  where o.workorderid= '" + workorderid + "'", "dataSource");
			log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());
			String curstep_id_map = null;
			String dealMessage;
			if (getSelectSQL.size() > 0) {
				curstep_id_map = getSelectSQL.get(0).get("curstep_id_map");
				log.debug("工单步骤流程id：	" + curstep_id_map);
				//下送1
				if (sys_source == 'YG' && sys_flag == '1') {
					outData = YGWorkOrderSend(sys_source, workorderid, business_source, eliteBean);
				//重新派遣2
				//} else if (sys_source == 'YG' && sys_flag == '2') {
					//outData = YGWorkOrderSend(sys_source, workorderid, source, eliteBean);
				//回访回退3
				//} else if (sys_source == 'YG' && sys_flag == '3') {
					//outData = YGWorkOrderSend(sys_source, workorderid, source, eliteBean);
				//延期审核回复4
				} else if (sys_source == 'YG' && sys_flag == '4') {
					outData = YGWorkOrderDelayedReply(sys_source, workorderid, approvalDays, eliteBean);
				}
			} else {
				dealMessage = "当前处理的工单在CRM系统不存在！";
				return "{\"resultcode\":\"0\",\"resultmessage\":\"\",\"data\":\"" + dealMessage + "\"}";
			}

		} catch (Exception e) {// 失败返回
			log.error("接口处理异常" + e.getMessage());
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

		}
		log.debug("完成返回结果:" + outData);

		return outData;
	}

	//调用运营管理下送接口
	public static String YGWorkOrderSend(String sys_source, String workorderid, String business_source, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();
		String limit=0;
		def cgobjective_guid;
		if(business_source=='9999B1') {
			def objectiveSQL = eliteBean.chaxun_sql("select top 1 objective_guid from objective where  workorderid = '" + workorderid + "'", "dataSource");
			if (objectiveSQL.size() > 0) {
				cgobjective_guid = objectiveSQL.get(0).get("objective_guid");
				def getLimitSQL = eliteBean.chaxun_sql("SELECT	TOP 1 sdct.limit AS limit FROM ( select limit,objective_guid,indate from SZWG_DE_Case_Tasks where  objective_guid='" + cgobjective_guid + "' UNION select limit,objective_guid,indate from SZWG_DE_Case_Tasks_his where  objective_guid='" + cgobjective_guid + "') sdct ORDER BY 	sdct.indate DESC", "dataSource");
				if (getLimitSQL.size() > 0) {
					limit = getLimitSQL.get(0).get("limit");
				}
			}
		}
		
		//判断流程时限是否为空 如果没有则默认取 limit_time 字段
		def getSelectSQL;
		/*2021-12-17 城管渠道处理实现需求调整-改为热线时限processing_time_limit
		if(limit=='0') {
			getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,case when t.business_source = 'CD38FF' then t.service  else c6.callnaturegroupdescription end AS comType,c.customername as comPerson,case when t.phone_number='' then c.mobile else t.phone_number end as linkTel,c.stringfield3 as userid,t.address as address,c1.yygh_codeid as compRange,o.createddate as compDate,s.staffname as person,c2.yygh_codeid as source,case when business_source='A13ACC' then t.content  when business_source='DBCA45' then t.content WHEN business_source = '9999B1' THEN t.case_describe else CONVERT(VARCHAR(100), t.description  COLLATE Chinese_PRC_CI_AS) end as complaints,t.location_x as x,t.location_y as y,t.loginname as assigner ,t._subunit as subunit,t._bmname as bmname,t.urgent as emerlevel,t.remarks+','+o.comments as remark,case when t.business_source = 'CD38FF' then t.subservice else c3.callnaturedescription end  AS comTypeTwo,case when t.business_source = '9999B1' then t.case_type when t.business_source = 'CD38FF' then t.busitype3 else c4.callnature3description end  AS comTypeThree,c5.yygh_codeid	as unitType,t.is_longsolve as issolve,t.subscribe_time as appointDate,case when business_source='A13ACC' then t.processing_time_limit  when business_source='DBCA45' then t.processing_time_limit when business_source='3E98AF' then t.processing_time_limit when business_source='9999B1' then DATEADD(ss,isnull(cast(t.limit_time as FLOAT),0),t.come_time) when business_source='CD38FF' then t.surplus_time else null end as dealTime,o.workorderid as taskCode from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.RELATION_ID=o.objective_guid LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid LEFT JOIN c_codetables c1 on c1.code_id=t.isstreet and c1.Use_Type='街道' LEFT JOIN staff s on s.staff_id=o.createdby LEFT JOIN c_codetables c2 on c2.code_id=t.business_source and c2.Use_Type='业务来源' LEFT JOIN callnature c3 on c3.callnature_id=t.business_type_2 LEFT JOIN callnature3 c4 on c4.callnature3_id=t.business_type_3 LEFT JOIN c_codetables c5 on c5.code_id=t.company_tpye and c5.Use_Type='单位类别'  LEFT JOIN callnaturegroup c6 on c6.callnaturegroup_id=t.business_type_1 where o.workorderid='" + workorderid + "'", "dataSource");
		}else {
			getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,case when t.business_source = 'CD38FF' then t.service  else c6.callnaturegroupdescription end AS comType,c.customername as comPerson,case when t.phone_number='' then c.mobile else t.phone_number end as linkTel,c.stringfield3 as userid,t.address as address,c1.yygh_codeid as compRange,o.createddate as compDate,s.staffname as person,c2.yygh_codeid as source,case when business_source='A13ACC' then t.content  when business_source='DBCA45' then t.content WHEN business_source = '9999B1' THEN t.case_describe else CONVERT(VARCHAR(100), t.description  COLLATE Chinese_PRC_CI_AS) end as complaints,t.location_x as x,t.location_y as y,t.loginname as assigner ,t._subunit as subunit,t._bmname as bmname,t.urgent as emerlevel,t.remarks+','+o.comments as remark,case when t.business_source = 'CD38FF' then t.subservice else c3.callnaturedescription end  AS comTypeTwo,case when t.business_source = '9999B1' then t.case_type when t.business_source = 'CD38FF' then t.busitype3 else c4.callnature3description end  AS comTypeThree,c5.yygh_codeid	as unitType,t.is_longsolve as issolve,t.subscribe_time as appointDate,case when business_source='A13ACC' then t.processing_time_limit  when business_source='DBCA45' then t.processing_time_limit when business_source='3E98AF' then t.processing_time_limit when business_source='9999B1' then DATEADD(ss,isnull(cast('" + limit + "' as FLOAT),0),t.come_time) when business_source='CD38FF' then t.surplus_time else null end as dealTime,o.workorderid as taskCode from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.RELATION_ID=o.objective_guid LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid LEFT JOIN c_codetables c1 on c1.code_id=t.isstreet and c1.Use_Type='街道' LEFT JOIN staff s on s.staff_id=o.createdby LEFT JOIN c_codetables c2 on c2.code_id=t.business_source and c2.Use_Type='业务来源' LEFT JOIN callnature c3 on c3.callnature_id=t.business_type_2 LEFT JOIN callnature3 c4 on c4.callnature3_id=t.business_type_3 LEFT JOIN c_codetables c5 on c5.code_id=t.company_tpye and c5.Use_Type='单位类别'  LEFT JOIN callnaturegroup c6 on c6.callnaturegroup_id=t.business_type_1 where o.workorderid='" + workorderid + "'", "dataSource");
			}
		*/
		getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,case when t.business_source = 'CD38FF' then t.service  else c6.callnaturegroupdescription end AS comType,c.customername as comPerson,case when t.phone_number='' then c.mobile else t.phone_number end as linkTel,c.stringfield3 as userid,t.address as address,c1.yygh_codeid as compRange,o.createddate as compDate,s.staffname as person,c2.yygh_codeid as source,case when business_source='A13ACC' then t.content  when business_source='DBCA45' then t.content WHEN business_source = '9999B1' THEN t.case_describe else CONVERT(VARCHAR(100), t.description  COLLATE Chinese_PRC_CI_AS) end as complaints,t.location_x as x,t.location_y as y,t.loginname as assigner ,t._subunit as subunit,t._bmname as bmname,t.urgent as emerlevel,t.remarks+','+o.comments as remark,case when t.business_source = 'CD38FF' then t.subservice else c3.callnaturedescription end  AS comTypeTwo,case when t.business_source = '9999B1' then t.case_type when t.business_source = 'CD38FF' then t.busitype3 else c4.callnature3description end  AS comTypeThree,c5.yygh_codeid	as unitType,t.is_longsolve as issolve,t.subscribe_time as appointDate,case when business_source='A13ACC' then t.processing_time_limit  when business_source='DBCA45' then t.processing_time_limit when business_source='3E98AF' then t.processing_time_limit when business_source='9999B1' then t.processing_time_limit when business_source='CD38FF' then t.processing_time_limit else null end as dealTime,o.workorderid as taskCode from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.RELATION_ID=o.objective_guid LEFT JOIN CUSTOMER c on c.customer_guid=o.customer_guid LEFT JOIN c_codetables c1 on c1.code_id=t.isstreet and c1.Use_Type='街道' LEFT JOIN staff s on s.staff_id=o.createdby LEFT JOIN c_codetables c2 on c2.code_id=t.business_source and c2.Use_Type='业务来源' LEFT JOIN callnature c3 on c3.callnature_id=t.business_type_2 LEFT JOIN callnature3 c4 on c4.callnature3_id=t.business_type_3 LEFT JOIN c_codetables c5 on c5.code_id=t.company_tpye and c5.Use_Type='单位类别'  LEFT JOIN callnaturegroup c6 on c6.callnaturegroup_id=t.business_type_1 where o.workorderid='" + workorderid + "'", "dataSource");
		
		String objective_guid = getSelectSQL.get(0).get("objective_guid");
		
		String comType,comPerson,linkTel,userid,address,compRange,compDate,person,source,complaints,x,y,assigner,subunit,bmname,emerlevel,remark,comTypeTwo,comTypeThree,unitType,issolve,appointDate,dealTime,taskCode="";
		comType = getSelectSQL.get(0).get("comType");
		comPerson = getSelectSQL.get(0).get("comPerson");
		linkTel = getSelectSQL.get(0).get("linkTel");
		userid = getSelectSQL.get(0).get("userid");
		address = getSelectSQL.get(0).get("address");
		compRange = getSelectSQL.get(0).get("compRange");
		person = getSelectSQL.get(0).get("person");
		source = getSelectSQL.get(0).get("source");
		complaints = getSelectSQL.get(0).get("complaints");
		x = getSelectSQL.get(0).get("x");
		y = getSelectSQL.get(0).get("y");
		assigner = getSelectSQL.get(0).get("assigner");
		subunit = getSelectSQL.get(0).get("subunit");
		bmname = getSelectSQL.get(0).get("bmname");
		emerlevel = getSelectSQL.get(0).get("emerlevel");
		remark = getSelectSQL.get(0).get("remark");
		comTypeTwo = getSelectSQL.get(0).get("comTypeTwo");
		comTypeThree = getSelectSQL.get(0).get("comTypeThree");
		unitType = getSelectSQL.get(0).get("unitType");
		issolve = getSelectSQL.get(0).get("issolve");
		taskCode = getSelectSQL.get(0).get("taskCode");
		compDate = getSelectSQL.get(0).get("compDate");
		appointDate = getSelectSQL.get(0).get("appointDate");
		dealTime = getSelectSQL.get(0).get("dealTime");
		
		//调试使用
		//String jsontemp ='comType='+comType+'&comPerson='+comPerson+'&linkTel='+linkTel+'&userid='+userid+'&address='+address+'&compRange='+compRange+'&compDate='+compDate+'&person='+person+'&source='+source+'&complaints='+complaints+'&x='+x+'&y='+y+'&assigner='+assigner+'&subunit='+subunit+'&bmname='+bmname+'&emerlevel='+emerlevel+'&remark='+remark+'&comTypeTwo='+comTypeTwo+'&comTypeThree='+comTypeThree+'&unitType='+unitType+'&issolve='+issolve+'&appointDate='+appointDate+'&dealTime='+dealTime+'&taskCode='+taskCode;
		//log.debug("处理前未加附件的json：" + jsontemp);
			
		comType = Getencode(comType);;
		comPerson =Getencode(comPerson);
		linkTel = Getencode(linkTel);
		userid= Getencode(userid);
		address=Getencode(address);
		compRange=Getencode(compRange);
		person=Getencode(person);
		source=Getencode(source);
		complaints=Getencode(complaints);
		x=Getencode(x);
		y=Getencode(y);
		assigner=Getencode(assigner);
		subunit=Getencode(subunit);
		bmname=Getencode(bmname);
		emerlevel=Getencode(emerlevel);
		remark=Getencode(remark);
		comTypeTwo=Getencode(comTypeTwo);
		comTypeThree=Getencode(comTypeThree);
		unitType=Getencode(unitType);
		issolve=Getencode(issolve);
		taskCode=Getencode(taskCode);

		//以下时间，排除null仅对空格做处理
		compDate=Getdateencode(compDate);
		appointDate=Getdateencode(appointDate);
		dealTime=Getdateencode(dealTime);
		
		String json ='comType='+comType+'&comPerson='+comPerson+'&linkTel='+linkTel+'&userid='+userid+'&address='+address+'&compRange='+compRange+'&compDate='+compDate+'&person='+person+'&source='+source+'&complaints='+complaints+'&x='+x+'&y='+y+'&assigner='+assigner+'&subunit='+subunit+'&bmname='+bmname+'&emerlevel='+emerlevel+'&remark='+remark+'&comTypeTwo='+comTypeTwo+'&comTypeThree='+comTypeThree+'&unitType='+unitType+'&issolve='+issolve+'&appointDate='+appointDate+'&dealTime='+dealTime+'&taskCode='+taskCode;
		log.debug("处理后未加附件的json：" + json);
		
		String TPURL = getProperty.get("CRM.TPURL");
		def getSelectUploadSQL = eliteBean.chaxun_sql("select CASE type WHEN 3 THEN	'"+ TPURL +"' + path ELSE path end as path  from rm_uploadrecord where  type in (1,3,5) and objectiveid='" + objective_guid + "'", "dataSource");
		Map<String, Object> map = new HashMap<String, Object>();
		String enclosure="";
		for (int i = 0; i < getSelectUploadSQL.size(); i++) {
			enclosure=enclosure+"&enclosure="+getSelectUploadSQL.get(i).get("path");
		}
		log.debug("getSelectUploadSQL:" + getSelectUploadSQL);
		log.debug("enclosure图片地址	" + enclosure);
		
		json=json+enclosure;
		log.debug("拼接图片地址的json：" + json);
		
		String reJson = null;
		try {
			String URL = getProperty.get("YYGL.URL") + "/callSendOrder";
			json=URL+"?"+json;
			log.debug("geturl:" + json);
			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			String injson =Util.doHttpPostUseHead(json,"","UTF-8",100000,0,headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String code = KHUtil.GetJV(inObject, "code");
			String message = KHUtil.GetJV(inObject, "message");

			long endTime = System.currentTimeMillis();
			if (code.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP运营管理系统下派接口处理成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + message + "\"}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP运营管理系统下派接口处理失败(" + message + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP运营管理系统下派接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}
	
	//调用运营管理延期审核回复接口
	public static String YGWorkOrderDelayedReply(String sys_source, String workorderid, String approvalDays, EliteBean eliteBean) {
		long startTime = System.currentTimeMillis();

		def getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,t.evtID as evtID,t.actInstID as actInstID,o.comments as comments from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN SZWG_DE_Case_Tasks sct on sct.actID=t.evtID  where o.workorderid= '" + workorderid + "'", "dataSource");
		String comments = getSelectSQL.get(0).get("comments");
		comments=Getencode(comments);
		String json ='taskCode='+workorderid+'&approvalDays='+approvalDays+'&approvalResponse='+comments;
		log.debug("json	" + json);
		
		String reJson = null;
		try {
			String URL = getProperty.get("YYGL.URL") + "/delayedReply";
			json=URL+"?"+json;
			log.debug("json	" + json);
			
			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			String injson =Util.doHttpPostUseHead(json,"","UTF-8",100000,0,headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String code = KHUtil.GetJV(inObject, "code");
			String message = KHUtil.GetJV(inObject, "message");

			long endTime = System.currentTimeMillis();
			if (code.equals("0")) {
				reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP运营管理系统延期审核回复接口处理成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + message + "\"}";
			} else {
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP运营管理系统延期审核回复接口处理失败(" + message + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
			}
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP运营管理系统延期审核回复接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}
		return reJson;
	}

	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
	// encode加密
	public static String Getencode(String getKey) {
		String Rev_Value = null;
		if(getKey==null) {
			Rev_Value="";
		}else {
			try {
					Rev_Value = URLEncoder.encode(getKey,"UTF-8");
				} catch (UnsupportedEncodingException e) {
					Rev_Value = "";
				}
		}
		return Rev_Value;
	}
	// encode时间加密
	public static String Getdateencode(String getKey) {
		String Rev_Value = null;
		if(getKey==null) {
			Rev_Value="";
		}else {
			try {
					Rev_Value = getKey.replace(" ","%20");;
				} catch (Exception e) {
					Rev_Value = "";
				}
		}
		return Rev_Value;
	}

}
